use actix_web::{get, post, web, Responder};
use crate::pojo::{FileData, File};
use walkdir::WalkDir;
use std::fs;
use crate::utils::{getIcon};
use crate::SHARED_PATH;
use serde::Deserialize;
use std::time::{UNIX_EPOCH};
use actix_web::web::{Query};

#[derive(Deserialize)]
struct FilepathQuery {
    filepath: Option<String>,
}


/// 文件列表
/// /api/files?filepath=/目录名
#[get("/api/files")]
pub async fn files(filepathQuery: Query<FilepathQuery>) -> impl Responder {
    let filepath = match &filepathQuery.filepath.as_ref() {
        Some(T) => T,
        None => ""
    };

    let mut data = FileData {
        virtualRoot: 0,
        currentMask: "RWD".to_string(),
        files: vec![],
    };

    // 遍历目录
    let currentSharedPath = SHARED_PATH.join(&*SHARED_PATH).join(filepath);
    let list = WalkDir::new(currentSharedPath.to_str().unwrap()).follow_links(true).max_depth(1);
    for item in list {
        let item = item.unwrap();
        let itemMetadata = fs::metadata(item.path()).unwrap();

        let time: String = itemMetadata.modified().unwrap().duration_since(UNIX_EPOCH).unwrap().as_millis().to_string();

        let curreryFile = File {
            name: item.file_name().to_str().unwrap().to_string(),
            dir: itemMetadata.is_dir(),
            size: itemMetadata.len(),
            modified: time,
            icon: getIcon(item.path().as_os_str().to_str().unwrap()),
            mask: "RWD".to_string(),
            guestMask: "RWD".to_string(),
            hasSubDir: false,
        };

        data.files.push(curreryFile);
    }

    return web::Json(data);
}

// 下载文件
#[get("/api/shared/{fileName}")]
pub async fn shared(web::Path(fileName): web::Path<String>) -> impl Responder {
    return format!("下载文件： {}", fileName);
}

/// 新建目录
/// /api/newdir
/// filepath: 目录名
#[post("/api/newdir")]
pub async fn newDir() -> impl Responder {
    // println!("{:?}", &from.filepath);
    // println!("新建目录：{}", filepath);
    // fs::create_dir(filepath);
    return "";
}